package com.channelsharing.hongqu.supplier.api.controller.coupon;

import com.channelsharing.common.entity.Paging;
import com.channelsharing.common.exception.SystemInnerBusinessException;
import com.channelsharing.hongqu.supplier.api.controller.BaseController;
import com.channelsharing.hongqu.supplier.api.entity.Coupon;
import com.channelsharing.hongqu.supplier.api.entity.UserCoupon;
import com.channelsharing.hongqu.supplier.api.service.CouponService;
import com.channelsharing.hongqu.supplier.api.service.UserCouponService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "优惠券功能")
@Validated
@RestController
@RequestMapping("/v1/coupon/")
public class CouponController extends BaseController {

    @Autowired
    private CouponService couponService;
    @Autowired
    private UserCouponService userCouponService;


    @ApiOperation(value = "创建一种优惠券")
    @PostMapping("add")
    public Coupon add(@RequestBody @Validated CouponAddRequestEntity couponAddRequestEntity){
        Coupon coupon = new Coupon();
        BeanUtils.copyProperties(couponAddRequestEntity, coupon);
        coupon.setSupplierId(super.currentSupplierUser().getSupplierId());

        Coupon result = couponService.addWithResult(coupon);
        return result;
    }

    @ApiOperation(value = "删除某种优惠券")
    @DeleteMapping("/{id}")
    public void delete(Long id){
        Coupon entity = new Coupon();
        entity.setId(id);
        entity.setSupplierId(super.currentSupplierUser().getSupplierId());

        List<UserCoupon> userCoupons = userCouponService.findListByCouponId(id);
        if(!userCoupons.isEmpty()){
            throw new SystemInnerBusinessException("优惠券已经被用户领取，无法进行删除");
        }

        couponService.delete(entity);
    }

    /**
     * 修改优惠券
     * @param couponModifyRequestEntity
     */
    @ApiOperation(value = "修改优惠券")
    @PatchMapping
    public void modify(@RequestBody @Validated CouponModifyRequestEntity couponModifyRequestEntity){
        List<UserCoupon> userCoupons = userCouponService.findListByCouponId(couponModifyRequestEntity.getId());
        if(!userCoupons.isEmpty()){
            throw new SystemInnerBusinessException("用户已经领取无法修改");
        }

        Coupon entity = new Coupon();
        BeanUtils.copyProperties(couponModifyRequestEntity, entity);

        couponService.modify(entity);
    }


    @ApiOperation(value = "获取优惠券列表")
    @GetMapping
    public Paging<Coupon> findPaging(
            @RequestParam(defaultValue = "0") Integer offset,
            @RequestParam(defaultValue = "10") Integer limit){

        Coupon entity = new Coupon();
        entity.setOffset(offset);
        entity.setLimit(limit);

        return couponService.findPaging(entity);

    }
}
